<?php
namespace frontend\controllers\base;

use yii\web\Controller;
use yii\web\UploadedFile;
use Yii;
use yii\web\View;
use common\models\Column;
use common\models\Cart;

class BaseController extends Controller
{
    public $EBusinessID='1283287';
    public $AppKey='55ad180d-29cb-4e14-bd78-8cea411eacfd';
    public $ReqURL='http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx';
    /**
     *
     * @param type $model
     *            model实例
     * @param type $rootPath
     *            保存路径
     * @param type $randName
     *            保存图片名
     * @param type $pk
     *            图片保存所属字段
     * @return string 图片名
     */
    public function upload($model, $name, $pk, $array = false, $rootPath = false, $randName = false)
    {
        if (! $rootPath)
            $rootPath = "uploads/{$name}/logo/" . date('Y-m-d') . '/';
        if (! file_exists($rootPath)) {
            mkdir($rootPath, 0700, true);
        }
        if ($array) {
            $file = UploadedFile::getInstances($model, $pk);
            if (! empty($file)) {
                $filenames = [];
                foreach ($file as $val) {
                    $ext = $val->getExtension();
                    $randName = time() . rand(1, 9999);
                    $filename = $rootPath . $randName . '.' . $ext;
                    if ($val->saveAs($filename)) {
                        $filenames[] = [
                            'id' => null,
                            'name' => $filename,
                            'pid' => $array
                        ];
                    }
                }
                return $filenames;
            }
        } else {
            if (! $randName)
                $randName = time() . rand(1, 9999);
            $file = UploadedFile::getInstance($model, $pk);
            $ext = $file->getExtension();
            $filename = $rootPath . $randName . '.' . $ext;
            $file->saveAs($filename);
            return $filename;
        }
    }

    public function actions()
    {
        parent::actions();
        return [
            'upload' => [
                'class' => 'kucha\ueditor\UEditorAction',
                'config' => [
                    "imagePathFormat" => "/uploads/" . \Yii::$app->controller->id . "/{yyyy}{mm}{dd}/{time}{rand:6}"
                ] // 上传保存路径

            ]
        ];
    }

    /**
     * 批量插入数据
     * 
     * @param type $model            
     * @param type $items            
     * @return boolean
     */
    public function insertAll($model, $items)
    {
        return Yii::$app->db->createCommand()
            ->batchInsert($model->tableName(), $model->attributes(), $items)
            ->execute();
    }
    // 无限极分类重组
    static function dataSort($data, $pid = 'pid')
    {
        $list = [];
        if (! empty($data)) {
            foreach ($data as $val) {
                $list[$val[$pid]][] = $val;
            }
        }
        return $list;
    }
    // 查询分类信息
    public function columnData()
    {
        $return = Column::find()->asArray()->all();
        $column = $this->dataSort($return);
        if (! empty($column)) {
            $view = Yii::$app->view;
            $view->params['column'] = $column;
        }
        return $return;
    }
    // 查询购物车
    public function showCart()
    {
        if ($uid = Yii::$app->user->id) {
            $cart = Cart::find()->where('uid=' . $uid)
                ->with('goods');
            $data=$cart->limit(4)->orderBy('id desc')
                ->asArray()
                ->all();
            $count=$cart->count();
            $view = Yii::$app->view;
            $view->params['cart'] = $data;
            $view->params['cartCount']=$count;
        }
    }
    public function curl($url,$post){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // post数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
    
    /**
     * Json方式 查询订单物流轨迹
     */
    public function getOrderTracesByJson($type,$num){
        $requestData= "{'OrderCode':'','ShipperCode':'{$type}','LogisticCode':'{$num}'}";
    
        $datas = array(
            'EBusinessID' => $this->EBusinessID,
            'RequestType' => '1002',
            'RequestData' => urlencode($requestData) ,
            'DataType' => '2',
        );
        $datas['DataSign'] = $this->encrypt($requestData, $this->AppKey);
        $result=$this->sendPost($this->ReqURL, $datas);
    
        //根据公司业务处理返回的信息......
    
        return $result;
    }
    
    /**
     *  post提交数据
     * @param  string $url 请求Url
     * @param  array $datas 提交的数据
     * @return url响应返回的html
     */
    public function sendPost($url, $datas) {
        $temps = array();
        foreach ($datas as $key => $value) {
            $temps[] = sprintf('%s=%s', $key, $value);
        }
        $post_data = implode('&', $temps);
        $url_info = parse_url($url);
        if(empty($url_info['port']))
        {
            $url_info['port']=80;
        }
        $httpheader = "POST " . $url_info['path'] . " HTTP/1.0\r\n";
        $httpheader.= "Host:" . $url_info['host'] . "\r\n";
        $httpheader.= "Content-Type:application/x-www-form-urlencoded\r\n";
        $httpheader.= "Content-Length:" . strlen($post_data) . "\r\n";
        $httpheader.= "Connection:close\r\n\r\n";
        $httpheader.= $post_data;
        $fd = fsockopen($url_info['host'], $url_info['port']);
        fwrite($fd, $httpheader);
        $gets = "";
        $headerFlag = true;
        while (!feof($fd)) {
            if (($header = @fgets($fd)) && ($header == "\r\n" || $header == "\n")) {
                break;
            }
        }
        while (!feof($fd)) {
            $gets.= fread($fd, 128);
        }
        fclose($fd);
    
        return $gets;
    }
    
    /**
     * 电商Sign签名生成
     * @param data 内容
     * @param appkey Appkey
     * @return DataSign签名
     */
    public function encrypt($data, $appkey) {
        return urlencode(base64_encode(md5($data.$appkey)));
    }
}